﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FTchina;
using System.Data;
using System.Collections;
using System.Text.RegularExpressions;

public partial class UI_menumanage : System.Web.UI.Page
{
    ArrayList ayl = new ArrayList();//存放要删除的菜单的id

    private static readonly Regex viewStateRegex =
              new Regex("<input type=\"hidden\" name=\"__VIEWSTATE\".*/>", RegexOptions.IgnoreCase); //过滤viewstate html标记的正则表达式


    private static readonly Regex endFormRegex =
        new Regex(@"</form>", RegexOptions.Multiline | RegexOptions.Compiled); //过滤 </form>标记的正则表达式

    string action = "";//list:列表 del:删除 mod:修改

    //重写HTML，过滤viewstate并输出
    protected override void Render(HtmlTextWriter writer)
    {
        System.IO.StringWriter stringWriter = new System.IO.StringWriter();
        HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
        base.Render(htmlWriter);

        string html = stringWriter.ToString();
        Match viewStateMatch = viewStateRegex.Match(html);
        string viewStateString = viewStateMatch.Captures[0].Value;//找出ViewState的Html标记 目的把viewstate的内容放到页面FORM的最后面加快加载速度和搜索抓录
        //  viewStateString = "<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\"\" />"; //仿博客园

        html = html.Remove(viewStateMatch.Index, viewStateMatch.Length);//替换掉ViewState的html标记

        Match endFormMath = endFormRegex.Match(html, viewStateMatch.Index);
        html = html.Insert(endFormMath.Index, viewStateString);//将ViewState的Html标记插入到</form>标记之前
        writer.Write(html);

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        basic.CheckAdmin(this);
        basic.ChkPoewr(this, FTchina.Api.htmlpath.GetCurrentPagePath());

        ddlmenupic.Attributes.Add("onchange", "return change(this.options[this.selectedIndex].value)");

        action = basic.FilterSQL(Request["action"]);
        if (action.Length == 0) action = "list";
        if (!IsPostBack)
        {
            LoadList();
            switch (action)
            {
                case "del": Delete(); break;
                case "mod": modify(); break;
            }
            plrootadd.Visible = true;
        }
    }

    private void modify()
    {
        plmodi.Visible = true;
        DataTable dt = shujuku.GetDataTable("select * from menulist where id=" + basic.FilterSQL(Request["id"]));

        txbyname.Text = dt.Rows[0]["context"].ToString();
       // if (txbyname.Text == "自定义表单") txbyname.Enabled = false;
        txbpx.Text = dt.Rows[0]["paixu"].ToString();
        txblink.Text = dt.Rows[0]["link"].ToString();
        ddlmenupic.Text = dt.Rows[0]["picpath"].ToString();
        chkpw.DataSource = shujuku.GetDataSet("select * from usergroup");
        chkpw.DataTextField = "groupname";
        chkpw.DataBind();

        //取出用户组角色
        string[] powers = dt.Rows[0]["power"].ToString().Split(',');
        if (powers.Length > 0)
        {
            ArrayList alpower = new ArrayList();
            for (int i = 0; i < powers.Length; i++)
            {
                alpower.Add(powers[i].ToString());
                 
            }
            
            

            for (int i = 0; i < chkpw.Items.Count; i++)
            {
                if (alpower.IndexOf(GetPowerIDByName( chkpw.Items[i].Value)) != -1)
                {
                    chkpw.Items[i].Selected = true;
                }
            }
        }

    }



    private void Delete()
    {
        string id = basic.FilterSQL(Request["id"]);
        if (id.Length == 0) { JS.Alert("不允许的操作！"); return; }
        ayl.Clear();
        //获取ID值
        GetAllId(id, 0);
        //删除分类条目
        DeleteFenleiID();

    }


    #region 加载分类



    /// <summary>
    /// 加载整个分类表
    /// </summary>
    private void LoadList()
    {

        litlist.Text = "";
        ddllm.Items.Clear();
        ddlold.Items.Clear();
        ddlnew.Items.Clear();
        int MTcount = 0;//执行遍历的次数
        //开始迭代加载
        MakeTr("0", MTcount);


        LoadMenuPics("~/images/icon/png/");



    }


    /// <summary>
    /// 生成菜单图片下拉列表
    /// </summary>
    /// <param name="p"></param>
    private void LoadMenuPics(string p)
    {
        ddlmenupic.Items.Clear();
      string [] lists=  FTchina.FileConfig.FileConfig.GetFileNames(Server.MapPath(p));
      foreach (string str in lists)
      {
          ddlmenupic.Items.Add(FTchina.FileConfig.FileConfig.GetFileName(str));
      }

    }
    /// <summary>
    /// 装配每一行
    /// </summary>
    /// <param name="id">上级ID</param>
    /// <param name="count">迭代次数</param>
    private void MakeTr(string id, int count)
    {

        DataView dv = new DataView(shujuku.GetDataTable("select * from menulist where parentid=" + id + " order by paixu desc,id desc"));

        string shanchu = string.Empty;//设置自定义表单不能删除


        foreach (DataRowView drv in dv)
        {
            // shanchu = (drv["context"].ToString() == "自定义表单") ? "" : "删除";//设置自定义表单不能删除
            shanchu = "删除";


            //菜单图标的处理

           // string menupicpath = (drv["picpath"].ToString().Trim().Length == 0) ? "" : "<img width='32' height='32' src='/images/icon/png/" + drv["picpath"].ToString().Trim() + "'>";
            string menupicpath = string.Empty;

            //形成表格
            litlist.Text += "<tr><td>" + MakeFelgefu(count) + drv["context"].ToString() + "</td><td>" + drv["paixu"].ToString() + "</td><td>" + GetPowerNamesByIds(drv["power"].ToString()) + "</td><td>" + drv["link"].ToString() + menupicpath + "</td><td> <a href=del.aspx?T=menulist&id=" + drv["id"].ToString() + "><a href='?action=mod&id=" + drv["id"] + "' >修改</a> <a href='?action=del&id=" + drv["id"] + "' title='header=[删除说明] body=[被删除项如果包含子项，那么所有的子项也将被删除]'>" + shanchu + "</a></td></tr>";

            //形成下拉列表
            ListItem li = new ListItem(MakeFelgefu(count) + drv["context"].ToString(), drv["id"].ToString());
            ddllm.Items.Add(li);
            ddlnew.Items.Add(li);
            ddlold.Items.Add(li);
            //再次遍历
            MakeTr(drv["id"].ToString(), count + 1);

        }

    }
    /// <summary>
    /// Make分隔符
    /// </summary>
    /// <param name="count"></param>
    /// <returns></returns>
    private string MakeFelgefu(int count)
    {
        string Returnwords = string.Empty;
        if (count == 0)
        {
            Returnwords = "";
        }

        else
        {
            Returnwords = ("├").PadLeft(count, '　');
        }
        return Returnwords;
    }

    #endregion

    #region 删除分类

    /// <summary>
    /// 获取系统要删除的对象的ID列表
    /// </summary>
    /// <param name="id"></param>
    private void GetAllId(string id, int count)
    {
        if (count == 0) { ayl.Add(id); }//第一次循环
        DataView dv = new DataView(shujuku.GetDataTable("select * from menulist where parentid=" + id + " order by id asc"));
        foreach (DataRowView drv in dv)
        {
          
            
                ayl.Add(drv["id"].ToString());

                GetAllId(drv["id"].ToString(), count + 1);
            
             
        }

    }
    /// <summary>
    /// 将ArrayList中的值转换为sql中的值
    /// </summary>
    /// <param name="aly"></param>
    /// <returns></returns>
    private string ArrayList2String(ArrayList aly)
    {
        string ReturnWords = "";
        foreach (string item in aly)
        {
            ReturnWords += item + ",";
        }
        ReturnWords = ReturnWords.Substring(0, ReturnWords.Length - 1);
        return ReturnWords;
    }
    /// <summary>
    /// 具体的执行删除的语句
    /// </summary>
    private void DeleteFenleiID()
    {
        string sql = "delete from menulist where id in (" + ArrayList2String(ayl) + ")";
       // Response.Write(sql);
        shujuku.ExecuteSql(sql);
        LoadList();
    }
    #endregion


    #region 按钮行为
    protected void btnziok_Click(object sender, EventArgs e)
    {
        string parentid = ddllm.SelectedValue.ToString();
        string context = basic.FilterSQL(txbzifl.Text);
        string sql = "insert into menulist (parentid,context) values(" + parentid + ",'" + context + "') ";
        UImsg.PageRender(shujuku.ExecuteSql(sql));

    }
    protected void btnroot_Click(object sender, EventArgs e)
    {
        string context = basic.FilterSQL(txbroot.Text);
        string sql = "insert into menulist (parentid,context) values('0','" + context + "') ";
        UImsg.PageRender(shujuku.ExecuteSql(sql));

    }
    protected void btnmodok_Click(object sender, EventArgs e)
    {
        string context = basic.FilterSQL(txbyname.Text);
        string id = basic.FilterSQL(Request["id"]);
        string paixu = basic.FilterSQL(txbpx.Text);
        string link = basic.SafeRequest(txblink.Text);
       // string menupic = ddlmenupic.SelectedValue;
        if (paixu.Length == 0) paixu = "0";
        //取权限的数组
        string power = string.Empty;
         
            foreach (ListItem item2 in chkpw.Items)
            {
                if (item2.Selected)
                {
                    power = power + GetPowerIDByName(item2.Text.ToString()) + ",";
                    //such as 1,9,13,
                }
            }
            if (power.EndsWith(","))
            {
                power = power.Substring(0, power.Length - 1);
            }
         

        //验证数据
        if (id.Length == 0 || context.Length == 0) { JS.Alert("请输入完整！"); return; }
        string sql = "update menulist set power='" +  power + "', link='" + link + "',paixu=" + paixu + ",context='" + context + "' where id=" + id;
       // basic.Log(sql);
        //将其底下的子菜单也更新权限
        string sqlchild = "update menulist set power='" + power + "' where parentid=" + id;
        UImsg.PageRender(shujuku.ExecuteSql(sql) && shujuku.ExecuteSql(sqlchild));

    }
    #endregion
    protected void btnmove_Click(object sender, EventArgs e)
    {
        string old = ddlold.SelectedValue;
        string newfenle = ddlnew.SelectedValue;
        string sql = "update menulist set parentid=" + newfenle + " where id=" + old;
        UImsg.PageRender(shujuku.ExecuteSql(sql));
    }


    protected Boolean CheckRoot()
    {
        return !shujuku.testread("select id from menulist where parentid=0");
    }


    /// <summary>
    /// 通过权限名称获取权限ID
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    protected String GetPowerIDByName(string name)
    {
        string sql = "select id from usergroup where groupname='" + name.Trim() + "'";
        //basic.Log(sql);
        return shujuku.GetDataTable(sql).Rows[0][0].ToString().Trim();
    }
    /// <summary>
    /// 通过权限ID获取权限名称
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    protected String GetPowerNameById(string id)
    {
        string sql = "select groupname from usergroup where id='" + id + "'";
       // basic.Log(sql);
        return shujuku.GetDataTable(sql).Rows[0][0].ToString().Trim();
    }


    /// <summary>
    /// 通过ids 获取 powernames
    /// </summary>
    /// <param name="ids">1,2,3</param>
    /// <returns>系统管理员,普通用户,审核组</returns>
    protected String GetPowerNamesByIds(string ids)
    {
        string tmp = string.Empty;
        if (ids.Contains(","))
        {
            foreach (string str in ids.Split(','))
            {
                if (str.Trim().Length > 0)
                {
                    tmp += GetPowerNameById(str.Trim()) + ",";
                }
            }
        }
        else
        {
            if (ids.Trim().Length > 0)
            {
                tmp = GetPowerNameById(ids);
            }
        }
        if (tmp.EndsWith(","))
        {
            tmp = tmp.Substring(0, tmp.Length - 1);
        }

        return tmp;
        
    }
}
